package com.zz.yt.lib.login.delegate.login;

import android.content.Context;
import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.blankj.utilcode.util.ThreadUtils;
import com.zz.yt.lib.login.R;
import com.zz.yt.lib.login.checker.TravelManager;
import com.zz.yt.lib.login.constant.ISignCodeListener;
import com.zz.yt.lib.login.constant.ISignUpListener;
import com.zz.yt.lib.login.delegate.login.base.BaseSigInDelegate;
import com.zz.yt.lib.ui.view.SelectCheckView;

import java.util.concurrent.TimeUnit;


/**
 * 登录
 *
 * @author qf
 * @version 2023-1-03
 */
public class SignInTravelDelegate extends BaseSigInDelegate {


    private Button loginSign;
    private EditText idEditCode;
    private TextView idTextCode;

    private SelectCheckView viewSelect = null;
    private ISignCodeListener mSignCodeListener = null;
    private ISignUpListener mSignUpListener = null;

    private int suspend = 1;
    private boolean isTiming = true;

    @Override
    public void onAttach(@NonNull Context activity) {
        super.onAttach(activity);
        if (activity instanceof ISignCodeListener) {
            mSignCodeListener = (ISignCodeListener) activity;
        }
        if (activity instanceof ISignUpListener) {
            mSignUpListener = (ISignUpListener) activity;
        }
    }

    @Override
    public Object setLayout() {
        return R.layout.hai_delegate_sign_in_travel;
    }

    private void inBundle() {
        if (mSignCodeListener != null) {
            Object launcher = mSignCodeListener.setSignIn();
            if (launcher != null) {
                if (launcher instanceof Integer) {
                    getImageView(R.id.login_image_background)
                            .setImageResource((int) launcher);
                } else if (launcher instanceof View) {
                    View viewLauncher = (View) launcher;
                    RelativeLayout view = findViewById(R.id.login_layout_background);
                    ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(
                            ViewGroup.LayoutParams.MATCH_PARENT,
                            ViewGroup.LayoutParams.MATCH_PARENT);
                    viewLauncher.setLayoutParams(layoutParams);
                    view.addView(viewLauncher);
                }
            }
        }

        //设置是否保存登录信息
        setSelect(true);

        viewSelect = findViewById(R.id.login_check_acc_pass);
        setImgSelect();

        //注册
        boolean isSignUp = false;
        if (mSignUpListener != null) {
            isSignUp = mSignUpListener.isSignUp();
            mSignUpListener.setSignUpView(mRootView, getTextView(R.id.login_text_sign_up));
        }
        getTextView(R.id.login_text_sign_up).setVisibility(isSignUp ? View.VISIBLE : View.GONE);
    }

    /*** 设置是否一周内自动登录 */
    private void setImgSelect() {
        if (viewSelect != null) {
            viewSelect.setChecked(TravelManager.isTravel());
            viewSelect.setOnClickListener(v -> {
                viewSelect.select();
                TravelManager.setRoleState(viewSelect.isChecked());
            });
        }
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, @NonNull View rootView) {
        inBundle();
        initView();
        inGradePermission();
    }

    private void initView() {
        getEditText(R.id.login_edit_phone).setText(getPhone());
        getEditText(R.id.login_edit_phone).setOnFocusChangeListener((v, hasFocus) -> {
            if (hasFocus) {
                findViewById(R.id.login_edit_phone).setBackgroundResource(R.drawable.frame_accent_r4);
            } else {
                findViewById(R.id.login_edit_phone).setBackgroundResource(R.drawable.frame_f4_r4);
            }
        });
        loginSign = getButton(R.id.login_btn_sign_in);
        idTextCode = getTextView(R.id.login_text_code);
        idEditCode = getEditText(R.id.login_edit_code);
        idEditCode.addTextChangedListener(this);
        idEditCode.setOnFocusChangeListener((v, hasFocus) -> {
            if (hasFocus) {
                idEditCode.setBackgroundResource(R.drawable.frame_accent_r4);
            } else {
                idEditCode.setBackgroundResource(R.drawable.frame_f4_r4);
            }
        });

        if (mSignCodeListener != null) {
            mSignCodeListener.setSignInView(loginSign);
        }
    }

    @Override
    protected void onGrantedSuccess() {
        idTextCode.setOnClickListener(view -> {
            if (mSignCodeListener != null) {
                String phone = getEditText(R.id.login_edit_phone)
                        .getText()
                        .toString()
                        .trim();
                if (isPhone(phone) && isTiming) {
                    mSignCodeListener.onPhoneCode(phone);
                    startTiming();
                }
            }
        });
        loginSign.setOnClickListener(view -> {
            if (isGranted()) {
                setInstallPermission();
                return;
            }
            if (mSignCodeListener != null) {
                String phone = getEditText(R.id.login_edit_phone)
                        .getText()
                        .toString()
                        .trim();
                String code = getEditText(R.id.login_edit_code)
                        .getText()
                        .toString()
                        .trim();

                if (isPhone(phone) && isCode(code)) {
                    mSignCodeListener.onPhoneSignIn(phone, code);
                }
            }
        });
    }


    /**
     * 计时
     */
    private void startTiming() {
        isTiming = false;
        suspend = 60;
        ThreadUtils.executeByFixedAtFixRate(1, new ThreadUtils.SimpleTask<String>() {

            @Override
            public String doInBackground() {
                return suspend > 0 ? suspend + " 秒" : "获取验证码";
            }

            @Override
            public void onSuccess(@Nullable String result) {
                if (idTextCode != null) {
                    idTextCode.setText(result);
                }
                suspend--;
                if (suspend < 0) {
                    isTiming = true;
                    cancel();
                }
            }
        }, 1, TimeUnit.SECONDS);
    }

    @Override
    public void afterTextChanged(Editable editable) {
        if (idEditCode != null && loginSign != null) {
            loginSign.setEnabled(idEditCode.getText().toString().trim().length() > 1);
        }
    }
}